//
//  WBComposeViewController.swift
//  XLWB
//
//  Created by MacBook on 16/7/9.
//  Copyright © 2016年 MacBook. All rights reserved.
//

import UIKit
import SVProgressHUD
class WBComposeViewController: UIViewController {

    @IBOutlet weak var textView: UITextView!
    
    @IBOutlet weak var toolbar: UIToolbar!
    //发布按钮
    @IBOutlet var sendButton: UIButton!
    //标题文本
    @IBOutlet var titleLabel: UILabel!
    
    //toolbar底部约束
    @IBOutlet weak var toolBarBottom: NSLayoutConstraint!
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
        //监听键盘通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //激活键盘
        textView.becomeFirstResponder()
    }

    override func viewDidAppear(_ animated: Bool) {
        //设置文本视图的代理
        textView.delegate = self
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //关闭键盘
        textView.resignFirstResponder()
        
    }
    //通知监听
    @objc private func keyboardChanged(n: Notification) {
    
        guard let rect = (n.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue(),
            duration = (n.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue
            else {
                return
        }

        //she˙i底部约束的高度
        let offset = view.bounds.height - rect.origin.y
        //更新底部约束
        toolBarBottom.constant = offset
        
        //动画更新约束
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
    }
    
    @objc private func close() {
        dismiss(animated: true, completion: nil)
    }
    
    //发布微博按钮监听方法
    @IBAction func postStatus() {
        
        print("发布微博")

        //获取微博文本
        guard let text = textView.text else {
            return
        }
        
        //发布微博
        // 2. 发布微博
        WBNetworkManager.shared.postStatus(text: text) { (result, isSuccess) in
            print(result)
            //修改指示器样式
            SVProgressHUD.setDefaultStyle(.dark)
            
            let message = isSuccess ? "发布成功" : "网络不给力"
            SVProgressHUD.showInfo(withStatus: message)
            //如果成功,延迟一段时间关闭当前窗口
            if isSuccess {
            
                DispatchQueue.main.after(when: DispatchTime.now() + 1) {
                
                    //恢复样式
                    SVProgressHUD.setDefaultStyle(.light)
                
                    self.close()
                }
            }
        }

    }
}
    
  

 //MARK-UITextViewDelegate
extension WBComposeViewController: UITextViewDelegate {

    //文本视图文字的变化
    func textViewDidChange(_ textView: UITextView) {
        sendButton.isEnabled = textView.hasText()
    }
}


private extension WBComposeViewController {

    func setupUI() {
    
        view.backgroundColor = UIColor.white()
        setupToolbar()
        setupNavigationBar()
    }
    
    //设置工具栏
    func setupToolbar() {
    
        let itemSettings = [["imageName": "compose_toolbar_picture"],
                            ["imageName": "compose_mentionbutton_background"],
                            ["imageName": "compose_trendbutton_background"],
                            ["imageName": "compose_emoticonbutton_background"],


                            ["imageName": "compose_add_background"]]
    
    //遍历数组
        var items = [UIBarButtonItem]()
        for s in itemSettings {
        
            guard let imageName = s["imageName"] else {
                continue
            }
        
            let image = UIImage(named: imageName)
            let imageHL = UIImage(named: imageName + "_highlighted")
            let btn = UIButton()
            
            btn.setImage(image, for: [])
            btn.setImage(imageHL, for: .highlighted)
            
            btn.sizeToFit()
            
//            //判断actionName
//            if let actionName = s["actionName"] {
//                
//                //给按钮添加监听方法
//                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
//            }
            //追加按钮
            items.append(UIBarButtonItem(customView: btn))
            //追加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
            
        
        }
    
        //删除末尾弹簧
        items.removeLast()
        toolbar.items = items
    }

    func setupNavigationBar() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(close))
        
        //发送按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        navigationItem.titleView = titleLabel
        
        sendButton.isEnabled = false
    }
}
